import Vue from 'vue'
import axios from 'axios'
import router from './router.js'
import qs from 'qs'
import { notify } from './ui'

axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
axios.defaults.baseURL = (process.env.NODE_ENV === 'production' ?
    'http://webhooks.cysmsc.cn'
    :
    'http://webhooks.test.kecms.cn')
    + '/api'


axios.defaults.withCredentials = true

axios.interceptors.request.use((d) => {
    d.headers['X-DRIVER'] = 'web'
    d.headers['X-REQUESTED-WITH'] = 'xmlhttprequest'

    if (d.headers['Content-Type'] !== 'multipart/form-data') {
        try {
            d.data = qs.stringify(d.data)
        } catch (e) {
            console.log(e)
        }
    }
    return d
})

axios.interceptors.response.use((d) => {
    return d.data
}, (err) => {
    if (err.response.status === 401) {
        router.push('/login')
    } else if (err.response.status === 403) {
        alert(err.response.data.errmsg)
        router.push('/login')
    } else {
        if (typeof err.config.autoerr === 'undefined' || err.config.autoerr) {
            let msg = '[' + err.response.status + ']'
            if (err.response.data) {
                const result = err.response.data
                if (result.error) {
                    msg = '[' + result.error.type + ']' + result.error.message
                } else {
                    msg += err.response.data.message
                    if (err.response.data.file) {
                        msg += '\r\n' + err.response.data.file + '(' + err.response.data.line + ')'
                    }
                }
            }
            notify.warning({
                title: '系统异常',
                message: msg
            })
            // $Alert(msg)
        } else {
            return Promise.reject(err.response)
        }
    }
})

Vue.prototype.$http = {
    get (url, params, options) {
        return axios.get(url, { params, ...options })
    },
    post (url, data, options) {
        return axios.post(url, data, options)
    },
    patch (url, data, options) {
        return axios.patch(url, data, options)
    },
    delete (url, data, options) {
        return axios.delete(url, Object.assign({}, {
            data: data
        }, options))
    }
}

export default axios
